package com.igeek.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 对c3p0进行简单的封装
 */
public class C3p0Util {

    /**
     * 1.创建连接池
     *      使用了单例模式，保证程序在运行时，只有一个连接池对象存在
     */
    private static final ComboPooledDataSource ds = new ComboPooledDataSource();

    public static ComboPooledDataSource getDs(){
        return ds;
    }

    /**
     * 2.获取连接对象
     * @return
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 3.资源关闭
     * @param conn
     * @param stat
     * @param rs
     */
    public static void close(Connection conn, Statement stat, ResultSet rs){
        try {

            if(conn != null){
                conn.close();
            }

            if(stat != null){
                stat.close();
            }

            if(rs != null){
                rs.close();
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
